//
//  InputKeyViewController.m
//  华康通
//
//  Created by leiyu on 16/9/13.
//  Copyright © 2016年 com.huakang. All rights reserved.
//

#import "InputKeyViewController.h"
#import "UMMobClick/MobClick.h"

@interface InputKeyViewController ()
@property (strong, nonatomic) IBOutlet UITextField *topTextField;
@property (strong, nonatomic) IBOutlet UITextField *bottomTextField;
@property (strong, nonatomic) IBOutlet UILabel *showColorLabel;
@property (strong, nonatomic) IBOutlet UIButton *nextButton;
//延迟请求后台数据的bool值
@property (nonatomic, unsafe_unretained) BOOL isSelected;
@property (strong, nonatomic) IBOutlet UIButton *isHiddenKeyButton;
//是否显示密码
@property (nonatomic, unsafe_unretained) BOOL isHiddenKey;


@end

@implementation InputKeyViewController




- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:LoadImage(@"back1") style:UIBarButtonItemStylePlain target:self action:@selector(popRootVC)];
    self.isHiddenKey = YES;
    self.isSelected = NO;
    self.showColorLabel.layer.cornerRadius = 6.0;
    self.showColorLabel.layer.masksToBounds = YES;
}

- (void)popRootVC
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"InputKeyViewController"];//("PageOne"为页面名称，可自定义)
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [SVProgressHUD dismiss];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [MobClick endLogPageView:@"InputKeyViewController"];
}

- (void)showAlertViewWithMsg:(NSString*)msg
{
    dispatch_async(dispatch_get_main_queue(), ^{
        CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
        TextStatusView *customView  = [TextStatusView view];
        customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
        customView.bottomLabel.text = msg;
        //    customView.layer.cornerRadius = 7.0;
        //    customView.layer.masksToBounds = YES;
        [alertView setContainerView:customView];
        [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确认", nil]];
        [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
            switch (buttonIndex)
            {
                case 0:
                    return ;
                    break;
                default:
                    return ;
                    break;
            }
        }];
        [alertView show];
    });
}

#pragma mark  //重置密码  修改密码

- (void)postVerificationCodeWithURL:(NSString*)url withParam:(NSDictionary*)param
{
    
    HKTShowNetworkView* networking = [HKTShowNetworkView shareInstance];
    [networking showErrorWithSuccess:^{
        
        [XHNetworking POST:url parameters:param success:^(NSData *responseObject) {
            id json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
            NSLog(@"重置密码  修改密码json = %@",json);
            if ([json isKindOfClass:[NSDictionary class]] && json)
            {
                if ([json[@"resultCode"] isEqualToString:@"0"])
                {
                    
                    dispatch_async(dispatch_get_global_queue(0, 0), ^{
                        if ([json[@"responseObject"][@"operationResult"] isEqualToString:@"0"])
                        {
                            
                            dispatch_async(dispatch_get_main_queue(), ^{
                                CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
                                TextStatusView *customView  = [TextStatusView view];
                                customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
                                customView.bottomLabel.text = json[@"responseObject"][@"resultMessage"];
                                //    customView.layer.cornerRadius = 7.0;
                                //    customView.layer.masksToBounds = YES;
                                [alertView setContainerView:customView];
                                [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确定",@"取消", nil]];
                                [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
                                    switch (buttonIndex)
                                    {
                                        case 0:
                                        {
                                            //去首页
                                            [self.navigationController popToRootViewControllerAnimated:YES];
                                            //                                    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                                            //                                    MyTabBarController* firstVC = [storyboard instantiateViewControllerWithIdentifier:@"TABBAR"];
                                            //                                    firstVC.index = 3;
                                            //                                    firstVC.selectedIndex = 3;
                                            //                                    [self presentViewController:firstVC animated:YES completion:nil];
                                        }
                                            break;
                                        default:
                                            return ;
                                            break;
                                    }
                                }];
                                [alertView show];
                            });
                        }
                        else
                        {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [self showAlertViewWithMsg:[NSString stringWithFormat:@"%@",json[@"responseObject"][@"resultMessage"]]];
                            });
                        }
                    });
                    
                    
                }
                else
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self showAlertViewWithMsg:[NSString stringWithFormat:@"%@",json[@"errorMessage"]]];
                    });
                }
            }
        } failure:^(NSError *error) {
            NSLog(@"发送验证码error = %@",error.userInfo);
        }];
        
    } failure:^{
        //展示广告图
        NSLog(@"检测到设备无网络连接！！！");
    }];
}
//是否显示密码
- (IBAction)isHiddenKey:(UIButton *)sender
{
    if (self.isHiddenKey)
    {
        self.bottomTextField.secureTextEntry = NO;
        self.topTextField.secureTextEntry = NO;
        [sender setImage:LoadImage(@"iconland16") forState:UIControlStateNormal];
    }
    else
    {
        self.bottomTextField.secureTextEntry = YES;
        self.topTextField.secureTextEntry = YES;
        [sender setImage:LoadImage(@"iconland15") forState:UIControlStateNormal];
    }
    self.isHiddenKey = !self.isHiddenKey;
}

//关闭键盘
- (IBAction)closeTextField:(UITextField *)sender
{
    [sender resignFirstResponder];
    //点next 进入再次输入密码
    [self.bottomTextField becomeFirstResponder];
}
//关闭键盘
- (IBAction)closeBottomKeyboard:(UITextField *)sender
{
    [self.topTextField resignFirstResponder];
    [self.bottomTextField resignFirstResponder];
    //点击密码键盘上的 go时  就会后台请求
    [self nextVC:self.nextButton];

}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

//上面那个输入框改变文字
- (IBAction)textChange:(UITextField *)sender
{
    [self judeColor];
}
//上面那个输入框改变文字
- (IBAction)bottomTextChange:(UITextField *)sender
{
    [self judeColor];
}
//按下瞬间改变提交label的背景颜色
- (IBAction)changeLabelColor:(UIButton *)sender
{
    if (![self.topTextField.text isEqualToString:@""] && ![self.bottomTextField.text isEqualToString:@""])
    {
        self.showColorLabel.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:22.0/255.0 blue:0.0 alpha:1.0];
        
        dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC));
        dispatch_after(delay, dispatch_get_main_queue(), ^{
            self.showColorLabel.backgroundColor = [UIColor colorWithPatternImage:LoadImage(@"login_btn.png")];
        });
    }
}


//判断按钮背景的颜色
- (void)judeColor
{
    if (![self.topTextField.text isEqualToString:@""] && ![self.bottomTextField.text isEqualToString:@""])
    {
        self.showColorLabel.backgroundColor = [UIColor colorWithPatternImage:LoadImage(@"login_btn.png")];
    }
    else
    {
        self.showColorLabel.backgroundColor = [UIColor colorWithRed:236.0/255.0 green:22.0/255.0 blue:0.0 alpha:0.1];
    }
}

//系统提示框
- (void)presentAlerControllerWithMessage:(NSString*)message withTextField:(UITextField*)textField
{
    NSLog(@"%@",message);
    [self.view endEditing:YES];
    CustomIOSAlertView *alertView = [[CustomIOSAlertView alloc] init];
    TextStatusView *customView  = [TextStatusView view];
    customView.frame = CGRectMake(10, 10, UISCREENWEITH - 80, ALERTVIEW_HEIGHT_B);
    customView.bottomLabel.text = message;
    //    customView.layer.cornerRadius = 7.0;
    //    customView.layer.masksToBounds = YES;
    [alertView setContainerView:customView];
    [alertView setButtonTitles:[NSMutableArray arrayWithObjects:@"确认", @"取消", nil]];
    [alertView setOnButtonTouchUpInside:^(CustomIOSAlertView *alertView, int buttonIndex) {
        switch (buttonIndex)
        {
            case 0:
            [textField becomeFirstResponder];
            break;
            default:
            NSLog(@"取消操作" );
            break;
        }
    }];
    [alertView show];
}


//提交（与后台交互）

- (IBAction)nextVC:(UIButton *)sender
{
    if (![self.topTextField.text isEqualToString:@""] && ![self.bottomTextField.text isEqualToString:@""])
    {
        //如果两次输入的密码一样，并且是大于8位小于16位的数字才可以（与后台交互）进入下一页面
        if ([self.topTextField.text isEqualToString:self.bottomTextField.text])
        {
            //非纯字母或者纯数字 高于8位
            if ([ExamineTool verityKeyWithString:self.bottomTextField.text])
            {
                if (self.isSelected)
                {
                    return;
                }
                self.isSelected = YES;
                [self performSelector:@selector(timeEnough) withObject:nil afterDelay:1.2];
            }
            //纯字母或者纯数字 或者少于8位
            else
            {
//                [self presentAlerControllerWithMessage:@"密码不符合规范！请重新输入！" withTextField:self.topTextField];
                ShowAlertView(@"密码不符合规范！请重新输入！",self.topTextField);
            }
        }
        else
        {
//            [self presentAlerControllerWithMessage:@"您两次输入的密码不一致！" withTextField:self.topTextField];
            ShowAlertView(@"您两次输入的密码不一致！",self.topTextField);
        }
    }
}


#pragma mark  //从本地数据库 提取用户注册的手机号码或者用户名

- (NSString*)getUserPhoneWithStr:(NSString*)str
{
    id info = [CacheData getCache:str];
    if (info && [info isKindOfClass:[NSData class]])
    {
        id json = [NSJSONSerialization JSONObjectWithData:info options:0 error:nil];
        if (json != nil && [json isKindOfClass:[NSDictionary class]])
        {
            return json[@"responseObject"][@"mobile"];
        }
        else
        {
            return @"";
        }
    }
    else
    {
        return @"";
    }
}

- (void)timeEnough
{
    [self.topTextField resignFirstResponder];
    [self.bottomTextField resignFirstResponder];
//    NSString* userName = [self getUserPhoneWithStr:@"regist"];
//    if ([userName isEqualToString:@""])
//    {
      NSString* userName = self.mobile;
//    }
    NSDictionary* json = @{@"platformType":@"1",
                           @"orderType":@"01",
                           @"requestService":@"updatePassword",
                           @"requestObject":@{@"customerName":userName,
                                              @"validateCodeMobile":self.mobile ,
                                              @"newPassword":self.bottomTextField.text,
                                              @"validateCode":self.verificationCode
                                              }
                           };
    //字符串转字符串
    NSString* str = [JSONToString dictionaryToJson:json];
    NSLog(@"修改密码json = %@",json);
    //转md5
    MyAdditions* md5 = [[MyAdditions alloc]init];
    md5.str = [NSString stringWithFormat:@"%@%@",KEY_POST,str];
    NSString* md5_Str = [md5 md5];
    NSString* url = [NSString stringWithFormat:@"%@&sign=%@",SERVER_URL,md5_Str];
    [self postVerificationCodeWithURL:url withParam:json];
    
    self.isSelected = NO;
}


@end
